package com.tanhua.sso.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;

/**
 * 用于读取RSA的公钥和私钥文件，如果文件不存在，就需要生成公钥和私钥文件
 */
@Service
@Getter
public class RSAService {

    private String publicKeyStr;
    private String privateKeyStr;

    @Value("${tanhua.rsa.dir}")
    private String rsaFileDir;

    @PostConstruct
    public void init() {
        //读取私钥文件
        File privateKeyFile = new File(rsaFileDir + File.separator + "rsa");
        if(privateKeyFile.exists()){
            this.privateKeyStr = FileUtil.readString(privateKeyFile, CharsetUtil.CHARSET_UTF_8);
        }

        //读取公钥
        File publicKeyFile = new File(rsaFileDir + File.separator + "rsa.pub");
        if(publicKeyFile.exists()){
            this.publicKeyStr = FileUtil.readString(publicKeyFile, CharsetUtil.CHARSET_UTF_8);
        }

        if(StrUtil.isAllNotEmpty(this.privateKeyStr, this.publicKeyStr)){
            return;
        }

        //生成RSA的公钥和私钥
        RSA rsa = new RSA();
        //写入公钥文件
        FileUtil.writeString(rsa.getPublicKeyBase64(), publicKeyFile, CharsetUtil.CHARSET_UTF_8);

        //写入私钥文件
        FileUtil.writeString(rsa.getPrivateKeyBase64(), privateKeyFile, CharsetUtil.CHARSET_UTF_8);

        this.privateKeyStr = rsa.getPrivateKeyBase64();
        this.publicKeyStr = rsa.getPublicKeyBase64();
    }

}
